package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.enums.StatusStaffEnum;
import com.xmy.cultivate.mapper.AdminMapper;
import com.xmy.cultivate.mapper.StaffMapper;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.CommonUtil;
import com.xmy.cultivate.util.Result;
import com.xmy.cultivate.util.ResultCode;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.tomcat.util.buf.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 登录账号 前端控制器
 * </p>
 *
 * @author min
 * @since 2022-07-19
 */
@RestController
@RequestMapping("/api/admin")
@Scope("prototype")
public class AdminController extends BaseController{

    @Autowired
    IAdminService iAdminService;

    @Resource
    AdminMapper adminMapper;

    @Resource
    StaffMapper staffMapper;

    @Autowired
    IRoleService iRoleService;

    @Autowired
    IRoleAdminService iRoleAdminService;

    @Autowired
    IPermissionService iPermissionService;

    @Autowired
    IAppointSchoolService iAppointSchoolService;

    @Autowired
    ICompanyService iCompanyService;

    @Autowired
    IMobileStaffPermissionService iMobileStaffPermissionService;

    @Autowired
    IAuthAdminContentService iAuthAdminContentService;

    @PostMapping(value = "/auth/logout")
    public Result logout(@RequestBody Map<String,Object> reMap){
        return new Result(Code.OK);
    }


    @GetMapping("/admin/getInfo")
    public Result getInfo(){
        Admin admin = this.adminModel;

        QueryWrapper<Staff> staffQueryWrapper = new QueryWrapper<>();
        staffQueryWrapper.eq("admin_id",admin.getId());
        Staff staff = staffMapper.selectOne(staffQueryWrapper);
        String username = "";
        Map<String,Object> data = new HashMap<>();
        if(staff != null){
            data.put("avatar",staff.getHeadImg());
            username = staff.getName();//真实姓名
            data.put("staffId",staff.getId());
        }else{
            data.put("avatar","");
        }
        if(admin.getIsSuper() == 1){
            username = "超级管理员";
        }
        data.put("username",username);//真实姓名

        data.put("admin_id",admin.getId());
        data.put("isSuper",admin.getIsSuper());
        data.put("name",admin.getAccount());


        /**
         * 校区
         */
        List<String> schoolNameList = new ArrayList<>();
        List<String> roleNameList = new ArrayList<>();
        if(admin.getGovernMode() == 1){
            schoolNameList.add("全部校区");
            //roleNameList.add("全角色");
        }else {
            schoolNameList = iAppointSchoolService.getSchoolNameListForForId(admin.getId(),2);
        }
        //获取角色
        roleNameList = iRoleAdminService.getAdminRoleNameList(admin.getId());

        data.put("schoolNameList",schoolNameList);
        data.put("roleNameList",roleNameList);


        List<String> roleIdList = new ArrayList<>();
        Set<String> permissionSet = new HashSet<>();
        Set<String> permissionFeatureSet = new HashSet<>();//功能权限

        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
        if(admin.getIsSuper() != 1){
            roleQueryWrapper.inSql("id","select role_id from role_admin where admin_id = "+admin.getId());
            String schoolIdListStr = "";
            for (Long id:admin.getSchoolIdList()){
                //schoolIdListStr = String.join(",",Long.toString(id));
                schoolIdListStr += id +",";
            }

            String finalSchoolIdListStr = schoolIdListStr;
            //System.out.print("schoolIdListStr："+schoolIdListStr);
            if(com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(finalSchoolIdListStr)){
                //去掉可最后一个逗号
                finalSchoolIdListStr = finalSchoolIdListStr.substring(0,finalSchoolIdListStr.length() -1);
                String finalSchoolIdListStr1 = finalSchoolIdListStr;
                roleQueryWrapper.and(i->i.eq("govern_mode",1).or().inSql("id","select for_id from appoint_school where type=5 and school_id in ("+ finalSchoolIdListStr1 +")"));
            }else {
                roleQueryWrapper.and(i->i.eq("govern_mode",1));
            }

            //roleQueryWrapper.//角色适用校区
            List<Role> roleList = new ArrayList<>();
            roleList = iRoleService.list(roleQueryWrapper);
            if(roleList.size()>0){
                for (Role role:roleList){
                    roleIdList.add(role.getId().toString());
                }
//                String roleIds =  StringUtils.join(roleIdList,',');
//                QueryWrapper<Permission> permissionQueryWrapper = new QueryWrapper<>();
//                permissionQueryWrapper.eq("type",1);//菜单
//                permissionQueryWrapper.inSql("id","select permission_id from role_permission where role_id in("+roleIds+")");
//                List<Permission> permissionList = iPermissionService.list(permissionQueryWrapper);
//                for (Permission permission:permissionList){
//                    permissionSet.add(permission.getCode());
//                }
//
//                permissionQueryWrapper = new QueryWrapper<>();
//                permissionQueryWrapper.eq("type",2);//功能
//                permissionQueryWrapper.inSql("id","select permission_id from role_permission where role_id in("+roleIds+")");
//                List<Permission> permissionFeatureList = iPermissionService.list(permissionQueryWrapper);
//                for (Permission permission:permissionFeatureList){
//                    permissionFeatureSet.add(permission.getCode());
//                }
            }

            List<String> mobileStaffPermissionList1 = iMobileStaffPermissionService.getStaffPermissionAllByStaffId(staff.getId(),1);//菜单
            List<String> mobileStaffPermissionList2 = iMobileStaffPermissionService.getStaffPermissionAllByStaffId(staff.getId(),2);//功能
            //分享的权限
            List<String> allotPermissonList = iAuthAdminContentService.getAllotCode(this.adminId);
            mobileStaffPermissionList1 = CommonUtil.getListUnion(mobileStaffPermissionList1,allotPermissonList);

            data.put("permissionList",mobileStaffPermissionList1);
            data.put("permissionFeatureList",mobileStaffPermissionList2);

        }else{
            roleIdList.add("super");
            permissionSet.add("isSuper");
        }
        data.put("roles",roleIdList);
        data.put("sourseLeve",this.sourseLeve);

        return new Result(Code.OK,data);
    }

}
